<?php

/**
 * Appstore每日排名跟踪 
 *
 * @author haifeng.wu
 */

require_once 'CommonController.php';

class Admin_AppstoreRankController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        $this->_loginIsCheck = 0;
        parent::init();
        $this->view->title = "管理中心";
        $this->_infoModel = new Application_Model_AppstoreInfo();
        $this->_rankModel = new Application_Model_AppstoreRank();
        $this->username = 'system';
        $api = array(
            'host' => 'itunes.apple.com', //api主机http://itunes.apple.com/
            'hostPort' => '80', //api主机端口
            'ssl' => false, //ssl
            'method' => 'POST', //获取数据方式
            'timeoutTime' => 1800, //连接超时时间，单位秒
            'logPath' => APPLICATION_PATH . '/../data/appLog'
        );
        $this->_api = new Application_Model_Api($api);
    }
    
    public function curlAction()
    {
        $sql = "SELECT * FROM {$this->_infoModel->getTableName()}";
        $rows = $this->_infoModel->getAdapter()->fetchAll($sql);
        $rankTmp = array();
        $time = date('Y-m-d H:i:s', time());
        foreach ($rows as $key => $val) {
            
            $rankArr = array();
            if(isset($rankTmp[$val['feedType']][$val['school']])){
                $rankArr = $rankTmp[$val['feedType']][$val['school']];
            } else {
                $url = str_replace('http://itunes.apple.com', '', $val['url']);
                $this->_api->setFile($url);
                $vars = array();
                $headers = array();
                $result = $this->_api->api($vars, $headers);
                $reg = "/<id im:id=\"(.*?)\" im:bundleId=\"(.*?)\">(.*?)<\/id>/";
                preg_match_all($reg, $result, $matches);
                foreach ($matches[1] as $key => $item) {
                    $exparr = array();
                    $exparr = explode('?', $item);
                    $frontarr = explode('/', $exparr[0]);
                    $rankArr[end($frontarr)] = $key + 1;
                }
                $rankTmp[$val['feedType']][$val['school']] = $rankArr;
            }
            $data['appstoreId'] = $val['appstoreId'];
            $val['appstoreId'] = str_replace('id','',$val['appstoreId']);
            $data['rank'] = isset($rankArr[$val['appstoreId']]) ? $rankArr[$val['appstoreId']] : '300+';
            $data['addTime'] = $time;
            $data['addUser'] = $this->username;
            dump($data);
            //$this->_rankModel->insert($data);
        }
        exit;
    }

    
    
}